package com.et114.components.validCode;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

//@author  guanhw

public class DrawRandNumber {
	private static final int		WIDTH		= 50;
	private static final int		HEIGHT		= 20;
	private static BufferedImage	image		= new BufferedImage (
														WIDTH ,
														HEIGHT ,
														BufferedImage.TYPE_INT_RGB );
	private static DrawRandNumber	instance	= new DrawRandNumber ( );
	private DrawRandNumber ( ) {
	}
	
	public static DrawRandNumber getInstance ( ) {
		return instance;
	}
	
	public synchronized String writeRandNumber ( int length ,
			HttpServletRequest request , String sessionName  ) throws IOException {
		String rand = getRandNumber ( length );
		setSession ( request ,sessionName , rand  );
		return rand;
	}
	
	public synchronized Image drawRandNumber ( int length ,
			HttpServletRequest request , String sessionName ) {
		String rand = getRandNumber ( length );
		Graphics g = image.getGraphics ( );
		refreshBgColor ( g );
		g.setColor ( getRandColor ( 20 , 130 ) );
		g.drawString ( rand , 6 , 16 );
		g.dispose ( );
		setSession ( request ,sessionName , rand  );
		return image;
	}
	
	private String getRandNumber ( int length ) {
		if ( length < 1 ) return null;
		String strChars[] = { "1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" };
		StringBuffer strPassword = new StringBuffer ( );
		int nRand = ( int ) Math.round ( Math.random ( ) * 100D );
		for ( int i = 0 ; i < length ; i ++ ) {
			nRand = ( int ) Math.round ( Math.random ( ) * 100D );
			strPassword.append ( strChars [ nRand % ( strChars.length - 1 ) ] );
		}
		return strPassword.toString ( );
	}
	
	private void setSession ( HttpServletRequest request , String sessionName ,  String rand ) {
		request.getSession ( ).setAttribute ( sessionName , rand );
	}
	
	public void refreshBgColor ( Graphics g ) {
		g.fillRect ( 0 , 0 , WIDTH , HEIGHT );
		g.setFont ( new Font ( "Times New Roman" , Font.PLAIN , 18 ) );
		g.setColor ( new Color( 1.0F , 0.75F , 0.0F , 0.45F ) );
		for ( int i = 0 ; i < 100 ; i ++ ) {
			int x = Constant.RANDOM.nextInt ( WIDTH );
			int y = Constant.RANDOM.nextInt ( HEIGHT );
			int xl = Constant.RANDOM.nextInt ( 12 );
			int yl = Constant.RANDOM.nextInt ( 12 );
			g.drawLine ( x , y , x + xl , y + yl );
		}
	}
	
	private Color getRandColor ( int fc , int bc ) {
		if ( fc > 255 )
			fc = 255;
		if ( bc > 255 )
			bc = 255;
		int r = fc + Constant.RANDOM.nextInt ( bc - fc );
		int g = fc + Constant.RANDOM.nextInt ( bc - fc );
		int b = fc + Constant.RANDOM.nextInt ( bc - fc );
		return new Color ( r , g , b );
	}
}